import Vue from 'vue'
import Vuex from 'vuex'
import {
    getToken,
    setToken,
    removeToken
} from '@/utils/auth'
Vue.use(Vuex)
import {
    Message,
    MessageBox
} from 'element-ui'
import { getUserInfoApi, logoutApi } from '@/api/user'
const defaultUserInfo = {
    userId: -1,
    avatar: "https://yaling.oss-cn-shenzhen.aliyuncs.com/yinxiu/nologin.jpg",
    username: "未登录",
    account: ""
}
export default new Vuex.Store({
    // state 中存放的就是全局共享的数据
    state: {
        userInfo: localStorage.getItem("userInfo") == null ? defaultUserInfo : JSON.parse(localStorage.getItem("userInfo")),
        token: getToken()
    },
    getters: {},
    // Mutation 用户变更Store数据
    mutations: {
        setUserInfo: (state, userInfo) => {
            state.userInfo = userInfo
            localStorage.setItem("userInfo", JSON.stringify(userInfo))
        },
        setToken: (state, token) => {
            state.token = token
            setToken(token)
        },
        logout: (state, userInfo) => {
            removeToken()
            localStorage.clear()
            state.userInfo = {}
            state.token = null
        }
    },
    actions: {
        // 获取用户信息
        //       如需要通过异步操作变更数据，必须通过Action，不可以使用Mutation
        // 使用Action改变数据时，还是会通过触发Mutation的方式间接变更数据
        GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfoApi({ userId: 1 }).then(response => {
                    console.log(response, '打印个人信息');
                    const data = response.data
                    commit('setUserInfo', data.data)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        }, // 登出
        LogOut({
            commit
        }) {
            return new Promise((resolve, reject) => {
                logoutApi().then((res) => {
                    if (res.data.code == 200) {
                        commit('logout', '')
                        Message({
                            message: '退出成功',
                            type: 'success',
                            duration: 1 * 1000
                        })

                    } else {
                        Message({
                            message: '退出失败',
                            type: 'error',
                            duration: 1 * 1000
                        })
                    }
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        }
    },
    modules: {}
})